package com.jcfy.project.module.client;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.jcfy.common.utils.http.HttpUtils;
import com.jcfy.framework.base.ClientBaseController;
import com.jcfy.framework.base.Error;
import com.jcfy.framework.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 小程序分享码
 *
 * @author jiangfeng
 * @date 2020-08-13
 */
@Api("小程序分享码")
@RestController
@RequestMapping("/client/qurcode")
public class QurcodeController extends ClientBaseController {

    /**
     * 小程序AppID
     */
    public static final String appId = "wx3810f0ec3e935e8a";
    /**
     * 小程序AppSecret
     */
    public static final String appSecret = "b0872a63abb1f834a8798911a9a91eb0";

    @Autowired
    private WxMaService wxMaService;

    /**
     * 生成小程序分享码(base64二进制流)
     *
     * @param scene
     * @param page
     * @param width
     * @return
     */
    @ApiOperation("生成小程序分享码(base64二进制流)")
    @PostMapping("/getQrcodeImage")
    public AjaxResult getQrcodeImage(String scene, String page, Integer width) {
        try {
            //获取AccessToken
            String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
            String param = "grant_type=client_credential&appid=APPID&secret=APPSECRET";
            param = param.replace("APPID", appId).replace("APPSECRET", appSecret);
            String access_token = HttpUtils.sendGet(accessTokenUrl, param);
            JSONObject jsonObject = JSONObject.parseObject(access_token);

            //组装url
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + jsonObject.getString("access_token");
            //组装参数
            Map<String, Object> params = new HashMap();
            //二维码携带参数 不超过32位
            params.put("scene", scene);
            //二维码跳转页面
            params.put("page", page);
            params.put("width", width);
            //执行post 获取数据流
            byte[] base64 = HttpUtils.sendPostImg(url, params);

//            // 设置小程序二维码线条颜色为黑色
//            WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
//            byte[] base64 = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(scene, page, width, false, lineColor, false);
            logger.info("[生成小程序码][状态#成功]");
            AjaxResult result = AjaxResult.success();
            result.put("base64", base64);
            return result;
        } catch (Exception e) {
            logger.error("[生成小程序码][状态#异常][原因# {}]", e.getMessage());
            return AjaxResult.error(Error._100000, e.getMessage());
        }
    }

}
